<template>
  <codemirror
    v-model="sqlCode"
    :placeholder="editorPlaceholder"
    :style="{ height: editorHeight + 'px' }"
    :autofocus="true"
    :indent-with-tab="true"
    :tabSize="tabSize"
    :extensions="extensions"
    :scrollbarStyle="null"
    @change="emit('change', $event)"
  />
  <!-- <div class="sql-format">
    <span @click="formatSql">格式化SQL</span>
    <span @click="clearVal">一键清空</span>
  </div> -->
</template>

<script setup>
import { Codemirror } from "vue-codemirror"
import { sql } from "@codemirror/lang-sql"
import { defineEmits, ref, defineProps, computed, onMounted, watch } from "vue"
import * as sqlFormatter from "sql-formatter"
onMounted(() => {
  sqlCode.value = props.value
})
const emit = defineEmits()
const props = defineProps({
  value: {
    type: String,
    default: ""
  },
  editorPlaceholder: {
    type: String,
    default: "请输入代码"
  },
  editorHeight: {
    type: String,
    default: "300"
  },
  tabSize: {
    type: Number,
    default: 2
  }
})
const _value = computed({
  get() {
    return props.value || ""
  },
  set(value) {
    emit("update:value", value)
  }
})
watch(
  () => props.value,
  (newValue) => {
    sqlCode.value = newValue
  }
)
const sqlCode = ref()
const extensions = ref([sql()])
//代码格式化
const formatSql = () => {
  sqlCode.value = sqlFormatter.format(sqlCode.value)
}
// 清除值
const clearVal = () => {
  sqlCode.value = ""
}
</script>
<style scoped lang="scss">
.sql-format {
  background-color: #f7f7f7;
  text-align: right;
  color: #2a99ff;
  padding: 10px;

  span:hover {
    cursor: pointer;
    text-decoration: underline;
  }

  > span:first-child {
    margin-right: 10px;
  }
}
</style>
